/*
 * AbstractFactoryXmlLoader.java
 * 
 * Created on Jul 3, 2007, 9:40:22 AM
 * 
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori.abstraction;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import java.io.FileInputStream;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author DGronau
 */
public class AbstractFactoryXmlLoader {

    private AbstractFactoryXmlLoader() {
    }

    public static void init(String fileName) {
        try {
            XMLReader xmlReader = new SAXParser();
            xmlReader.setContentHandler(new FactoryHandler());
            InputSource is = new InputSource(new FileInputStream(fileName));
            xmlReader.parse(is);
        } catch(Exception ex) {
            throw new IllegalArgumentException(ex);
        }
    }
    
    private static class FactoryHandler extends DefaultHandler {
        
        private AbstractFactory abstractFactory;
        
        @Override
        @SuppressWarnings("unchecked")
        public void startElement(String uri, String localName, String qName, Attributes attributes){
            if ("abstractFactory".equals(qName)) {
                String className = attributes.getValue("class");
                try {
                    Class clazz = Class.forName(className);
                    abstractFactory = (AbstractFactory) clazz.getMethod("getInstance").invoke(null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new IllegalArgumentException(ex);
                }
            } else if("factory".equals(qName)) {
                String key = attributes.getValue("key");
                String className = attributes.getValue("class");
                try {
                   Factory<?> factory = (Factory<?>) Class.forName(className).newInstance(); 
                   abstractFactory.register(key, factory);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new IllegalArgumentException(ex);
                }   
            } 
        }

    }
    
    
}
